#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <lcthw/dbg.h>
#include <lcthw/mystdio.h>
//   implement



void num2str(char *str, int num) {
	char tmp[20];
	if (num < 0) {
		*str++ = '-';
		num = -num;
	}
	int len = 0;
	if (num == 0) tmp[len++] = '0';
	else while (num) {
		tmp[len++] = num % 10 + '0';
		num = num / 10;
	}
	while (len-- > 0) {
		*str++ = tmp[len];
	}
    *str = '\0';
	return ;
}


int mysprintf(char *out, const char *fmt, ...) {
    va_list ap;
    int len; 
    va_start(ap, fmt); 
    len=myvsprintf(out,fmt,ap);
    va_end(ap);
    return len;
}
int myvsprintf(char *out, const char *fmt, va_list ap) {
    int d;
	char stmp[20];
    char *s;
    char *str = out;
    while (*fmt != '\0')
    {
        if(*fmt != '%'){
            *(str++) = *(fmt++);
            continue;
        }
        fmt++;//%后面是占位符d，s，c...
        switch (*fmt){
        case 'd':
            d = va_arg(ap,int);
            printf("d:%d\n",d); 
            num2str(stmp,d);
            printf("s:%s\n",stmp); 
            for (size_t i = 0; stmp[i] != '\0'; i++)
            {
                *str++ = stmp[i];
            }
            break;
        case 's':
            s=va_arg(ap,char *);
            printf("s:%s\n",s);
            while(*s != '\0') *str++ = *s++;
            printf("out + s:%s\n",out);          
            break;        
        default:
            if(*fmt == '%') 
                *(str++) = '%';    // %% ==> 输出字符%
            else 
                return -1; // 不是% d s return error
            break;
        }
        fmt++;
    }
    *str = '\0';
    // printf("out:%s\n",out)  ;      
    // printf("strlen out:%ld\n",strlen(out))  ;  
    return str-out;
}


